package com.mo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mo.entity.Menu;
import com.mo.entity.params.UserSearchParams;
import com.mo.entity.PageVo;
import com.mo.entity.User;
import com.mo.mapper.MenuMapper;
import com.mo.mapper.UserMapper;
import com.mo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;

    @Override
    public PageVo<User> list(UserSearchParams params) {
        Page<User> userPage = new Page<>(params.getPageNum(), params.getPageSize());
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
                .orderByDesc(User::getUserId)
                .like(StringUtils.isNotBlank(params.getRealName()), User::getRealName, params.getRealName())
                .like(StringUtils.isNotBlank(params.getUsername()), User::getUsername, params.getUsername())
                .like(StringUtils.isNotBlank(params.getPhone()), User::getPhone, params.getPhone());
        Page<User> selectPage = this.baseMapper.selectPage(userPage, wrapper);

        // 不把密码发送给前端
        List<User> records = selectPage.getRecords();
        records = Optional.ofNullable(records).orElse(new ArrayList<>())
                .stream()
                .peek(user -> user.setPassword(null))
                .collect(Collectors.toList());

        PageVo<User> pageVo = new PageVo<>();
        pageVo.setPageSize(selectPage.getSize());
        pageVo.setPageNum(selectPage.getCurrent());
        pageVo.setTotal(selectPage.getTotal());
        pageVo.setList(records);
        return pageVo;
    }

    @Override
    public String[] getUserAuthorityById(String userId) {
        List<Menu> menus = menuMapper.getUserMenuByUserId(Integer.valueOf(userId));
        return Optional.ofNullable(menus).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .filter(menu -> menu.getType().equals("2"))
                .map(Menu::getPermissionCode)
                .toArray(String[]::new);
    }
}




